<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
  import * as echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'

  const animationDuration = 2000

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      },
      data: {
        type: Array,
        default: []
      }
    },
    data() {
      return {
        chart: null
      }
    },
    watch: {
      data: {
        deep: true,
        handler(newVal, oldVal) {
          this.data = newVal
          this.initChart()
        }
      },
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart()
      })
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')
        let xData = []
        let yData = []
        this.data.forEach(item => {
          xData.push(item.name)
          yData.push(item.value)
        });
        this.chart.setOption({

          tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          grid: {
            top: 100,
            left: '4%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category',
            data: xData,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#666'
              }
            },
            splitLine: {
              show: true
            },
          }],
          yAxis: [{
            type: 'value',
            name: '百分比（%）',
            axisLabel: {
              formatter: '{value} %'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#666'
              }
            },
            splitLine: {
              show: true
            },
            data: [2, 20, 40, 60, 80, 100]
          }],
          series: [{
            name: '百分比',
            type: 'bar',
            stack: 'vistors',
            barWidth: '20px',
            data: yData,
            animationDuration
          }]
        })
      }
    }
  }

</script>
